<template>
  <div class="email-config">
    <div class="header">
      <h1>邮箱配置管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        添加配置
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-card>
      <el-table :data="configs" v-loading="loading">
        <el-table-column prop="smtp_host" label="SMTP服务器" />
        <el-table-column prop="smtp_port" label="端口" width="80" />
        <el-table-column prop="smtp_user" label="用户名" />
        <el-table-column prop="from_name" label="发件人名称" />
        <el-table-column prop="from_email" label="发件人邮箱" />
        <el-table-column label="安全连接" width="100">
          <template #default="{ row }">
            <el-tag :type="row.smtp_secure ? 'success' : 'warning'">
              {{ row.smtp_secure ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '激活' : '未激活' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" @click="testConfig(row)">测试</el-button>
            <el-button
              size="small"
              type="success"
              @click="activateConfig(row)"
              :disabled="row.is_active"
            >
              激活
            </el-button>
            <el-button size="small" type="primary" @click="editConfig(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteConfig(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑邮箱配置' : '创建邮箱配置'"
      v-model="showCreateDialog"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="SMTP服务器" prop="smtp_host">
          <el-input v-model="form.smtp_host" placeholder="例如: smtp.163.com" />
        </el-form-item>
        <el-form-item label="SMTP端口" prop="smtp_port">
          <el-input-number v-model="form.smtp_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="安全连接" prop="smtp_secure">
          <el-switch v-model="form.smtp_secure" />
        </el-form-item>
        <el-form-item label="用户名" prop="smtp_user">
          <el-input v-model="form.smtp_user" placeholder="邮箱地址" />
        </el-form-item>
        <el-form-item label="密码/授权码" prop="smtp_pass">
          <el-input
            v-model="form.smtp_pass"
            type="password"
            placeholder="邮箱密码或授权码"
            show-password
          />
        </el-form-item>
        <el-form-item label="发件人名称" prop="from_name">
          <el-input v-model="form.from_name" placeholder="走失宠物协寻平台" />
        </el-form-item>
        <el-form-item label="发件人邮箱" prop="from_email">
          <el-input v-model="form.from_email" placeholder="邮箱地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 测试对话框 -->
    <el-dialog title="测试邮箱配置" v-model="showTestDialog" width="400px">
      <el-form :model="testForm" label-width="100px">
        <el-form-item label="测试邮箱">
          <el-input
            v-model="testForm.test_email"
            placeholder="输入接收测试邮件的邮箱地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTestDialog = false">取消</el-button>
        <el-button type="primary" @click="submitTest" :loading="testing">
          发送测试邮件
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getEmailConfigs,
  createEmailConfig,
  updateEmailConfig,
  deleteEmailConfig,
  activateEmailConfig,
  testEmailConfig,
  type EmailConfig,
  type CreateEmailConfigParams
} from '@/api/emailConfig'

const loading = ref(false)
const submitting = ref(false)
const testing = ref(false)
const showCreateDialog = ref(false)
const showTestDialog = ref(false)
const isEdit = ref(false)
const configs = ref<EmailConfig[]>([])
const formRef = ref<FormInstance>()
const currentConfig = ref<EmailConfig | null>(null)

const form = reactive<CreateEmailConfigParams>({
  smtp_host: 'smtp.163.com',
  smtp_port: 587,
  smtp_secure: true,
  smtp_user: '',
  smtp_pass: '',
  from_name: '走失宠物协寻平台',
  from_email: ''
})

const testForm = reactive({
  test_email: ''
})

const rules: FormRules = {
  smtp_host: [{ required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }],
  smtp_port: [{ required: true, message: '请输入SMTP端口', trigger: 'blur' }],
  smtp_user: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  smtp_pass: [{ required: true, message: '请输入密码或授权码', trigger: 'blur' }],
  from_name: [{ required: true, message: '请输入发件人名称', trigger: 'blur' }],
  from_email: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 获取配置列表
const fetchConfigs = async () => {
  try {
    loading.value = true
    const response = await getEmailConfigs()
    console.log('前端收到的响应:', response)
    // 由于响应拦截器的处理，response直接就是数据数组
    configs.value = response
    console.log('设置后的configs:', configs.value)
  } catch (error) {
    console.error('获取邮箱配置失败:', error)
    ElMessage.error('获取邮箱配置失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    smtp_host: 'smtp.163.com',
    smtp_port: 587,
    smtp_secure: true,
    smtp_user: '',
    smtp_pass: '',
    from_name: '走失宠物协寻平台',
    from_email: ''
  })
  formRef.value?.resetFields()
}

// 编辑配置
const editConfig = (config: EmailConfig) => {
  isEdit.value = true
  currentConfig.value = config
  Object.assign(form, {
    smtp_host: config.smtp_host,
    smtp_port: config.smtp_port,
    smtp_secure: config.smtp_secure,
    smtp_user: config.smtp_user,
    smtp_pass: '', // 不显示原密码
    from_name: config.from_name,
    from_email: config.from_email
  })
  showCreateDialog.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value && currentConfig.value) {
      await updateEmailConfig(currentConfig.value.id, form)
      ElMessage.success('邮箱配置更新成功')
    } else {
      await createEmailConfig(form)
      ElMessage.success('邮箱配置创建成功')
    }

    showCreateDialog.value = false
    resetForm()
    fetchConfigs()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

// 激活配置
const activateConfig = async (config: EmailConfig) => {
  try {
    await activateEmailConfig(config.id)
    ElMessage.success('邮箱配置激活成功')
    fetchConfigs()
  } catch (error) {
    ElMessage.error('激活失败')
  }
}

// 测试配置
const testConfig = (config: EmailConfig) => {
  currentConfig.value = config
  testForm.test_email = ''
  showTestDialog.value = true
}

// 提交测试
const submitTest = async () => {
  if (!currentConfig.value) return

  try {
    testing.value = true
    await testEmailConfig(currentConfig.value.id, testForm)
    ElMessage.success('测试邮件发送成功')
    showTestDialog.value = false
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    testing.value = false
  }
}

// 删除配置
const deleteConfig = async (config: EmailConfig) => {
  try {
    await ElMessageBox.confirm('确定要删除这个邮箱配置吗？', '确认删除', {
      type: 'warning'
    })

    await deleteEmailConfig(config.id)
    ElMessage.success('删除成功')
    fetchConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchConfigs()
})

// 监听对话框关闭
const handleDialogClose = () => {
  isEdit.value = false
  currentConfig.value = null
  resetForm()
}
</script>

<style scoped>
.email-config {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}
</style>
